package cn.wolfcode.cloud.shop.web.controller;


import cn.wolfcode.cloud.shop.anno.UserParam;
import cn.wolfcode.cloud.shop.domain.User;
import cn.wolfcode.cloud.shop.resp.Result;
import cn.wolfcode.cloud.shop.service.IUserService;
import cn.wolfcode.cloud.shop.util.CookieUtil;
import cn.wolfcode.cloud.shop.util.DBUtil;
import cn.wolfcode.cloud.shop.util.MD5Util;
import cn.wolfcode.cloud.shop.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.RandomAccessFile;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author Administrator
 */
@RestController
@RequestMapping("/tokens")
@Validated
public class TokenController {

    @Autowired
    private IUserService userService;

    @RequestMapping("/login")
    public Result<?> login(@Valid LoginVo loginVo, HttpServletResponse response){
        //返回值属性的设计
        //{code,msg,data}
        String token = userService.login(loginVo.getMobile(),loginVo.getPassword());
        CookieUtil.addCookie(response,CookieUtil.TOKEN_IN_COOKIE_NAME,token);
        return Result.success();
    }


    @GetMapping
    public Result<User> getCurrent(@UserParam User user){
        System.out.println("====>"+user.getId());
        return Result.success(user);
    }

    @RequestMapping("/initData")
    public Result<String> initData() throws Exception {
        List<User> users = initUser(500);//在内存中创建500个User对象
        insertToDb(users);//把500个User对象保存到数据库中
        createToken(users);//通过500个User对象，调用service方法，模拟登陆，创建500个token,然后存在磁盘文件中.(jmeter)
        return Result.success("");
    }

    private void createToken(List<User> users) throws Exception {
        File file = new File("D:/tokens.txt");
        if (file.exists()) {
            file.delete();
        }
        RandomAccessFile raf = new RandomAccessFile(file, "rw");
        file.createNewFile();
        raf.seek(0);
        for (int i = 0; i < users.size(); i++) {
            LoginVo vo = new LoginVo();
            vo.setMobile(users.get(i).getId() + "");
            vo.setPassword(MD5Util.inputPass2FormPass("123456"));
            String token = userService.login(vo.getMobile(), vo.getPassword());
            String row = users.get(i).getId() + "," + token;
            raf.seek(raf.length());
            raf.write(row.getBytes());
            raf.write("\r\n".getBytes());
        }
        raf.close();
    }

    private void insertToDb(List<User> users) throws Exception {
        Connection conn = DBUtil.getConn();
        String sql = "insert into t_user(login_count, nickname, register_date, salt, password, id)values(?,?,?,?,?,?)";
        PreparedStatement pstmt = conn.prepareStatement(sql);
        for (int i = 0; i < users.size(); i++) {
            User user = users.get(i);
            pstmt.setInt(1, user.getLoginCount());
            pstmt.setString(2, user.getNickname());
            pstmt.setTimestamp(3, new Timestamp(user.getRegisterDate().getTime()));
            pstmt.setString(4, user.getSalt());
            pstmt.setString(5, user.getPassword());
            pstmt.setLong(6, user.getId());
            pstmt.addBatch();
        }
        pstmt.executeBatch();
        pstmt.close();
        conn.close();
    }

    private List<User> initUser(int count) {
        List<User> users = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            User user = new User();
            user.setId(13000000000L + i);
            user.setLoginCount(1);
            user.setNickname("user" + i);
            user.setRegisterDate(new Date());
            user.setSalt("1a2c3d4e");
            user.setPassword(MD5Util.formPass2DbPass(MD5Util.inputPass2FormPass("123456"), user.getSalt()));
            users.add(user);
        }
        return users;
    }
}
